import { useUserStore } from '@/pinia/modules/user'
import { useRouterStore } from '@/pinia/modules/router'
import router from '@/router/index'
import Nprogress from 'nprogress'
// const res = getMenu()
// console.log(res, 'res')

const whiteList = ['Login']

const getRouter = async() => {
  const routerStore = useRouterStore()
  await routerStore.SetAsyncRouter()
}

async function handleKeepAlive(to) {
  if (to.matched.some(item => item.meta.keepAlive)) {
    if (to.matched && to.matched.length > 2) {
      for (let i = 1; i < to.matched.length; i++) {
        const element = to.matched[i - 1]
        if (element.name === 'Layout') {
          to.matched.splice(i, 1)
          await handleKeepAlive(to)
        }
        // 如果没有按需加载完成则等待加载
        if (typeof element.components.default === 'function') {
          await element.components.default()
          await handleKeepAlive(to)
        }
      }
    }
  }
}

router.beforeEach(async(to, from) => {
  const routerStore = useRouterStore()
  Nprogress.start()
  const userStore = useUserStore()
  to.meta.matched = [...to.matched]
  handleKeepAlive(to)
  const token = userStore.token

  if (to.meta.client) {
    return true
  }
  if(to.meta.title){//判断是否有标题
    document.title = to.meta.title
}
  // 在白名单
  if (whiteList.indexOf(to.name) > -1) {
    if (token) {
      if (!routerStore.asyncRouterFlag) {
        await getRouter()
      }
      return { path: '/' }
    } else {
      return true
    }
  } else {
    // 不在白名单中并且已经登录的时候
    if (token) {
      // 添加flag防止多次获取动态路由和栈溢出
      if (!routerStore.asyncRouterFlag) {
        await getRouter(userStore)
        if (router.hasRoute(to.name)) {
          return true
        } else {
          return { path: '/404' }
        }
      } else {
        if (to.matched.length) {
          return true
        } else {
          return { path: '/404' }
        }
      }
    } else {
      return {
        name: 'Login'
      }
    }
  }
})

router.afterEach(() => {
  // 路由加载完成后关闭进度条
  document.getElementsByClassName('main-cont main-right')[0]?.scrollTo(0, 0)
  Nprogress.done()
})

router.onError(() => {
  // 路由发生错误后销毁进度条
  Nprogress.remove()
})
